package com.youxin.cpcenter.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Comparator;
import java.util.Date;

import com.youxin.busfoundation.bean.classify.RequestClassifyIndustryBean;
import com.youxin.busfoundation.bean.classify.ResponseCityBean;
import com.youxin.busfoundation.bean.classify.ResponseClassifyBean;
import com.youxin.busfoundation.bean.ent.RequestCompanyInfoBean;
import com.youxin.busfoundation.bean.region.RequestRegionBean;
import com.youxin.busfoundation.common.es.*;
import com.youxin.busfoundation.common.es.bean.*;
import com.youxin.busfoundation.common.name.NameOperator;
import com.youxin.cpcenter.common.dbcache.CacheDataObject;
import com.youxin.cpcenter.dao.TbEntMemberInfoMapper;
import com.youxin.cpcenter.dao.TbEntOrderMiddlePhoneRecordMapper;
import com.youxin.cpcenter.model.TbEntOrderMiddlePhoneRecord;
import com.youxin.cpcenter.service.ClassifyService;
import com.youxin.cpcenter.service.ConfigSearchCompanyService;
import com.youxin.cpcenter.service.LeadsService;
import com.youxin.cpcenter.service.RegionService;
import com.youxin.foundation.interfaces.Convert;
import com.youxin.foundation.utils.ArrayUtils;
import com.youxin.foundation.utils.DateUtil;
import com.youxin.foundation.utils.StringUtils;
import com.youxin.foundation.utils.collections.CollectionsUtils;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youxin.busfoundation.bean.ent.QueryEntMemberBean;
import com.youxin.busfoundation.bean.ent.RequestEntInfo;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.bean.phone.QueryPhoneLatestTime;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.enums.EnterpriseScaleType;
import com.youxin.busfoundation.enums.SearchType;
import com.youxin.busfoundation.utils.es.EsBasePage;
import com.youxin.busfoundation.utils.security.AESCode;
import com.youxin.busfoundation.utils.security.AesUtils;
import com.youxin.busfoundation.utils.security.SecurityAES;
import com.youxin.cpcenter.service.SearchService;
import com.youxin.cpcenter.service.ViewLeadsService;

/**
 * @desc 公司线索接口实现
 * @author yingde.cao
 */
@Service("searchService")
public class SearchServiceImpl extends BaseServiceImpl implements SearchService {

	@Autowired
	private ClassifyService classifyService;

	@Autowired
	private TbEntOrderMiddlePhoneRecordMapper tbEntOrderMiddlePhoneRecordMapper;

	@Autowired
	private ViewLeadsService viewLeadsService;

	@Autowired
	private LeadsService leadsService;

	@Autowired
	private TbEntMemberInfoMapper tbEntMemberInfoMapper;
	
	@Autowired
	private ConfigSearchCompanyService configSearchCompanyService;

	public static List<String> convertIndustry(List<Object> list)
	{
		if(ArrayUtils.isEmpty(list))
		{
			return new ArrayList<>();
		}
		List<String> indutrys=new ArrayList<>(list.size());
		for(Object obj:list){
			if(obj instanceof Integer)
			{
				indutrys.add(String.valueOf(obj));
			}
		}
		return indutrys;
	}
	/**
	 * 分类转换编码
	 */
	private Convert<CompanyInfoBean> convertCompanyInfo = (t) -> {
		try {
//			List<Object> objects=CollectionsUtils.listClassConvert(t.getIndustry());
//			t.setIndustry(convertIndustry(objects));
//			objects=CollectionsUtils.listClassConvert(t.getIndustrySmall());
//			t.setIndustrySmall(convertIndustry(objects));
			List<String> industryName = CacheDataObject.instance().getIndustryName(t.getIndustry(), classifyService);
			t.setIndustryName(industryName);
			List<String> industrySmallName = CacheDataObject.instance().getIndustryName(t.getIndustrySmall(),
					classifyService);
			t.setIndustrySmallName(industrySmallName);

		} catch (Exception e) {
			logger.error("convertCompanyInfo异常", e);
		}

		try {
			t.getArea().sort(new Comparator<Integer>() {
				@Override
				public int compare(Integer o1, Integer o2) {
					return o1.compareTo(o2);
				}
			});
			// t.setArea(area);
			List<String> regionNames = CacheDataObject.instance().getRegionNames(t.getArea(), classifyService);
			t.setAreaName(regionNames);
		} catch (Exception e) {
			logger.error("convertCompanyInfo regionNames异常", e);
		}
	};

	/**
	 * 线索信息转换编码
	 */
	private Convert<CompanyLeadsBean> convertLeadInfo = (t) -> {
		try {
			List<String> industryName = CacheDataObject.instance().getIndustryName(t.getIndustry(), classifyService);
			t.setIndustryName(industryName);
			List<String> industrySmallName = CacheDataObject.instance().getIndustryName(t.getIndustrySmall(),
					classifyService);
			t.setIndustrySmallName(industrySmallName);
		} catch (Exception e) {
			logger.error("convertLeadInfo异常", e);
		}
	};

	/**
	 * 搜索公司线索
	 */
	public EsBasePage<Object> identifySearch(RequestQueryLeadsBean requestBean) throws Exception {
		if (requestBean.getType() == SearchType.CompanyType.getValue()
				|| requestBean.getType() == SearchType.CompanyProType.getValue()) {
			EsBasePage<Object> result = new SearchComapny<CompanyInfoBean>().queryList(requestBean,
					CompanyInfoBean.class);
			return result;
		} else {
			return new SearchResource<CompanyLeadsBean>(convertLeadInfo).queryList(requestBean, CompanyLeadsBean.class);
		}
	}

	/**
	 * 搜索公司线索
	 */
	public EsBasePage<Object> search(RequestQueryLeadsBean requestBean) throws Exception {
		UserInfo userInfo = LoginAuth.getUserInfo();
		if (requestBean.getType() == SearchType.CompanyType.getValue()
				|| requestBean.getType() == SearchType.CompanyProType.getValue()) {
			List<CompanyInfoBean> list=null;
			EsBasePage<Object> result=null;
			/**
			 * 空的搜索请求
			 */
			if(requestBean.isEmptySearch())
			{
				list=configSearchCompanyService.selectDefaultSearchList(requestBean.getPageSize(),convertCompanyInfo);
				setCompanyInfoProperties(list,userInfo);
				requestBean.setResults(CollectionsUtils.listClassConvert(list));
				requestBean.setPageNo(1);
				requestBean.setTotalRecord(list.size());
				return requestBean;
			}
			result = new SearchComapny<CompanyInfoBean>(convertCompanyInfo).queryList(requestBean,
					CompanyInfoBean.class);
			list = CollectionsUtils.listClassConvert(result.getResults());
			/**
			 * 搜索分类区域,以下是处理匹配当前搜索的分类,如果搜索的分类,需要展示的是命中的分类信息
			 */
			setCompanyInfoSearchIndustry(requestBean,list);

			setCompanyInfoProperties(list,userInfo);
			return result;
		} else {
			return new SearchResource<CompanyLeadsBean>(convertLeadInfo).queryList(requestBean, CompanyLeadsBean.class);
		}
	}
	/**
	 * 搜索分类区域,以下是处理匹配当前搜索的分类,如果搜索的分类,需要展示的是命中的分类信息
	 * @param requestBean
	 * @param list
	 */
	private void setCompanyInfoSearchIndustry(RequestQueryLeadsBean requestBean,List<CompanyInfoBean> list)
	{		
		List<String> industry = requestBean.getIndustry();
		List<String> industrySmaill = requestBean.getIndustrySmall();
		boolean isIndustry = !ArrayUtils.isEmpty(industry);
		boolean isIndustrySmall = !ArrayUtils.isEmpty(industrySmaill);
		if (isIndustry || isIndustrySmall) {
			for (CompanyInfoBean item : list) {
				int index = -1;
				if (isIndustry) {
					index = CollectionsUtils.interIndex(item.getIndustry(), industry);
					if (index >= 0) {
						item.setIndustryMain(item.getIndustry().get(index));
						item.setIndustryMainName(item.getIndustryName().get(index));
						continue;
					}
				}
				if (isIndustrySmall) {
					index = CollectionsUtils.interIndex(item.getIndustrySmall(), industrySmaill);
					if (index >= 0) {
						item.setIndustryMain(item.getIndustrySmall().get(index));
						item.setIndustryMainName(item.getIndustrySmallName().get(index));
						continue;
					}
				}
			}
		}
	}
	
	/**
	 * 设置已读联系人数量等信息
	 * @param list
	 * @param userInfo
	 */
	private void setCompanyInfoProperties(List<CompanyInfoBean> list,UserInfo userInfo)
	{
		viewLeadsService.updateLeadsViewStatus(list, userInfo.getEntMemberId());
		leadsService.updateLeadsStatus(list, userInfo.getEntIdentifyId());
		setContactInfo(list);
	}

	private void setContactInfo(List<CompanyInfoBean> list) {
		if (ArrayUtils.isEmpty(list)) {
			return;
		}
		List<? extends Bucket> contactList = null;
		try {
			List<String> uids = list.stream().map(item -> item.getUid()).collect(Collectors.toList());
			contactList = new SearchContact<ContactCountBean>().queryContactCount(uids);
		} catch (Exception e) {
		}
		
		if (contactList == null) {
			return;
		}
		Map<String, Long> contactMap = new HashMap<>(contactList.size());
		for (Bucket item : contactList) {
			contactMap.put(item.getKeyAsString(), item.getDocCount());
		}
		for (CompanyInfoBean item : list) {
			Long contactCount = contactMap.get(item.getUid());
			if (contactCount != null) {
				item.setContactNo(contactCount.intValue());
			}
		}
	}

	/**
	 * 企业画像查询
	 */
	public CompanyInfoBean searchCompany(RequestEntInfo requestBean) throws Exception {
		return new SearchComapny<CompanyInfoBean>().queryCompanyInfo(requestBean);
	}

	/**
	 * 联系人查询
	 */
	public EsBasePage<Object> searchContact(RequestContactBean requestsBean) throws Exception {
		UserInfo userInfo = LoginAuth.getUserInfo();
		EsBasePage<Object> results = new SearchContact<ContactBean>((t) -> {

		}).queryList(requestsBean, ContactBean.class);
		List<ContactBean> list = CollectionsUtils.listClassConvert(results.getResults());
		if (!ArrayUtils.isEmpty(list)) {
			QueryEntMemberBean queryEntMemberBean = new QueryEntMemberBean();
			queryEntMemberBean.setCompanyUid(requestsBean.getCompanyUid());
			List<String> mobiles = list.stream().filter((t) -> !StringUtils.isNullOrEmpty(t.getMobile())).map((t) -> {
				return t.getMobile();
			}).collect(Collectors.toList());

			for (ContactBean item : list) {
				item.setRealName(item.getName());
				//todo:联系人头衔 2018-1-5
				if (StringUtils.isNullOrEmpty(item.getTitle())) {
					item.setPosition(NameOperator.hidePosition(item.getTitle()));
				} else {
                    item.setPosition("");
				}
			}

			if (!ArrayUtils.isEmpty(mobiles)) {
				queryEntMemberBean.setMobiles(mobiles);
				List<String> queryResults = tbEntMemberInfoMapper.selectByCompanyUidAndMobiles(queryEntMemberBean);
				for (ContactBean item : list) {
					/**
					 * 不是企业版成员
					 */
					if (!queryResults.contains(item.getMobile())) {
						String name = NameOperator.hideName(item.getName());
						item.setName(name);
						String position = NameOperator.hidePosition(item.getTitle());
						item.setTitle(position);
					}
				}
				QueryPhoneLatestTime latestTimeBean = new QueryPhoneLatestTime();
				latestTimeBean.setCallPhone(userInfo.getPhone());
				latestTimeBean.setPhones(mobiles);
				List<TbEntOrderMiddlePhoneRecord> records = tbEntOrderMiddlePhoneRecordMapper
						.selectLatestTimeByPhone(latestTimeBean);
				if (!ArrayUtils.isEmpty(records)) {
					for (ContactBean item : list) {
						for (TbEntOrderMiddlePhoneRecord record : records) {
							if (item.getMobile().equals(record.getAnswerPhone())) {
								Date callDate = new Date(record.getAddTime());
								String latestTime = DateUtil.dateToString(callDate, "yyyy.MM.dd HH:mm");
								item.setLatestTime(latestTime);
								break;
							}
						}
					}
				}
			}
			for (ContactBean t : list) {
				try {
					if (!StringUtils.isNullOrEmpty(t.getMobile())) {
						String mobile = AesUtils.encrypt(t.getMobile(), String.valueOf(userInfo.getId()));
						t.setMobile(mobile);
					}
				} catch (Exception e) {
				}

				try {
					if (!StringUtils.isNullOrEmpty(t.getTelephone())) {
						String telphone = AesUtils.encrypt(t.getTelephone(), String.valueOf(userInfo.getId()));
						t.setTelephone(telphone);
					}
				} catch (Exception e) {
				}
			}
		}
		return results;
	}

	/**
	 * 企业资源
	 */
	public List<ResourceBean> searchResource(RequestResourceBean requestsBean) throws Exception {
		return new SearchResource<ResourceBean>().query(requestsBean, ResourceBean.class);
	}

}
